# 支付回调
from fastapi import APIRouter, Request, Depends
from fastapi.responses import HTMLResponse
from peewee_async import Manager

from common.g.g import G_CLIENT, G_REDIS
from common.pkg.ali.client import AliClient
from common.utils.depends.common import get_mgw
from common.utils.resp import JsonResponse, RC
from service.pay_way_service import TenantPayConfigService

router = APIRouter(prefix="/callback")


@router.post("/ali/notify")
async def alipay_callback(request: Request,
                          mgw: Manager = Depends(get_mgw)
                          ):
    data = await request.form()
    appid = data.get("appid")
    tpcs = TenantPayConfigService(mgw, G_REDIS)
    ok, data_or_code = await tpcs.get_ali_pay_config_by_appid(appid)
    if ok:
        ali_client = AliClient(client=G_CLIENT, **data_or_code.data)
        if ali_client.verify_async_response(data):
            # todo 业务逻辑处理


            return HTMLResponse("success")
    return HTMLResponse("success")
